<?php
/**
 * 微博接口测试
 * @author Chunyang.Jiang<chunyang@staff.sina.com.cn>
 * @date 2011-03-31
 */
class WeiboClient
{
	protected $_WB_AKEY = '';
	protected $_WB_SKEY = '';
	
	public function __construct($wb_akey, $wb_skey)
	{
		$this->_WB_AKEY = $wb_akey;
		$this->_WB_SKEY = $wb_skey;
	}
	
	public function mkTokenUrl()
	{
		
	}
	
	public function getRequestToken()
	{
		
	}
}

function FetchCUrl($method, $api, $param=array())
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Sae T OAuth v0.2.0-beta2');//用户代理
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);//连接超时
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);//超时
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//是否返回Header消息
	curl_setopt($ch, CURLOPT_ENCODING, '');//默认编码
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	if ( strtoupper($method) == 'POST' ){
		curl_setopt($ch, CURLOPT_POST, true);
	}
	//$param['oauth_signature'] = baseUrl($method, $api, $param);
	$key_parts = url_rfc3986($param);
	$key = implode('&', $key_parts);
	var_dump($key);
	$base_string = baseUrl('GET', $api, $param);
	$param['oauth_signature'] = base64_encode(hash_hmac('sha1', $base_string, $key, true));
	foreach ( $param as $var=>$val ){
		$paramStr[] = "$var=$val";
	}
	$url = 'http://api.t.sina.com.cn/' . $api . "?" . implode('&', $paramStr);
	echo $base_string;
	//echo $param['oauth_signature'];exit();
	curl_setopt($ch, CURLOPT_URL, $url);
	$data = curl_exec($ch);
	return $data;
	//curl_setopt($ch, $option, $value);
}

function baseUrl($method, $api, $param)
{
	$url = $method . '&' . urlencode('http://api.t.sina.com.cn/' . $api) . '&';
	foreach ($param as $var=>$val){
		$paramStr[] = urlencode($var) . '%3D' . urlencode($val);
	}
	$url .= implode('%26', $paramStr);
	//echo $url . '<br />';
	//$url .= '%26';
	return $url;
}

function url_rfc3986($input)
{
	if (is_array($input)){
		return array_map('url_rfc3986', $input);
	}elseif (is_scalar($input)){
		return str_replace(
			'+', 
			' ', 
			str_replace('%7E', '~', rawurlencode($input))
		);
	}else{
		return '';
	}
}

class curl
{
	public static $_hanle = null;
	
	private function __construct()
	{
		;
	}
	
	public static function getInstance()
	{
		if (!self::$_hanle || !(self::$_hanle instanceof self)){
			self::$_hanle = new self();
		}
		return self::$_hanle;
	}
	
	private function curl_init($url, $param)
	{
		curl_init();
	}

	public function fetchApi($method='post', $api, $param=array())
	{
		$curl = curl_init();
		curl_setopt($curl, CURL_NETRC_IGNORED, '');
	}
}